#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>

#define BUFSIZE 128

int main(void)
{
	int pfd[2] = {};
	pid_t pid;

	if (-1 == pipe(pfd)) {
		perror("Error creating pipe");
		exit(1);
	}
	pid = fork();
	if (0 == pid) {
		int ret;
		char buf[BUFSIZE] = {};

		close(pfd[1]); // 关闭子进程写
		while (1) {
			ret = read(pfd[0], buf, BUFSIZE);
			if (-1 == ret) {
				perror("Error reading from pipe");
				exit(1);
			}
			if (0 == ret) {
				break;
			}
			write(1, buf, ret);
		}
		close(pfd[0]); // 关闭子进程读
		exit(0);
	}
	
	close(pfd[0]); // 关闭父进程读
	sleep(1);
	write(pfd[1], "Hello world\n", 12);
	sleep(1);
	close(pfd[1]); // 关闭父进程写

	wait(NULL);

	return 0;
}
